<template>
  <div v-if="complaintHistory.length === 0" class="text-center p-5 text-gray-500">暂无历史投诉记录</div>
  <div v-else>
    <div v-for="(item, index) in complaintHistory" :key="index" class="bg-white rounded-lg shadow-sm p-4 mb-4">
      <div class="flex justify-between items-start">
        <div class="flex-1">
          <div class="flex items-center mb-2">
            <span class="text-gray-600 mr-2">订单编号：</span>
            <span class="font-medium">{{ item.businessOrderId }}</span>
          </div>
          <div class="flex items-center mb-2">
            <span class="text-gray-600 mr-2">投诉服务人员：</span>
            <span class="font-medium">{{ getServicePersonName(item.servicePersonId) }}</span>
          </div>
          <div class="flex items-center mb-2">
            <span class="text-gray-600 mr-2">投诉内容：</span>
            <span class="font-medium">{{ item.complaintContent }}</span>
          </div>
          <div class="flex items-center mb-2">
            <span class="text-gray-600 mr-2">投诉时间：</span>
            <span>{{ formatDate(item.complaintTime) }}</span>
          </div>
          <div class="flex items-center">
            <span class="text-gray-600 mr-2">处理状态：</span>
            <span
              :class="{
                'text-green-500': item.status === '已解决',
                'text-yellow-500': item.status === '待解决',
                'text-red-500': item.status === '已拒绝',
              }"
              >{{ item.status }}</span
            >
          </div>
        </div>
        <div class="text-right">
          <span class="text-blue-500 text-sm cursor-pointer" @click="toggleExpand(index)">
            {{ item.expanded ? "收起" : "展开详情" }}
          </span>
        </div>
      </div>
      <div v-if="item.expanded" class="mt-3 pt-3 border-t border-gray-100">
        <div class="flex items-center mb-2">
          <span class="text-gray-600 mr-2">处理回复：</span>
          <span>{{ item.resolution || "--" }}</span>
        </div>
        <div class="flex items-center mb-2">
          <span class="text-gray-600 mr-2">服务时间：</span>
          <span>{{ item.serviceStartTime }}</span>
        </div>
        <div class="flex items-center">
          <span class="text-gray-600 mr-2">备注：</span>
          <span>{{ item.remarks }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from "vue";
import { getcusComplaintHistory } from "@/api/customer";
import { getserComplaintHistory } from "@/api/service";
import { uerPersonStore } from "@/store/modules/person";

const customerId = uni.getStorageSync("userId");

const customerType = uni.getStorageSync("usertype");
const usepersonStore = uerPersonStore();

// 历史投诉数据
const complaintHistory = reactive([]);

// 服务人员数据
const servicePersonnel = ref([]);

// 切换卡片展开/收起状态
const toggleExpand = (index) => {
  complaintHistory[index].expanded = !complaintHistory[index].expanded;
};

// 获取历史投诉数据的逻辑
const fetchComplaintHistory = async () => {
  try {
    let res;
    if (customerType === "customer") {
      res = await getcusComplaintHistory(customerId);
    } else if (customerType === "service") {
      res = await getserComplaintHistory(customerId);
    } else {
      console.warn("未知的用户类型:", customerType);
      return;
    }

    if (res && res.code === 200) {
      Object.assign(
        complaintHistory,
        res.data.map((item) => ({ ...item, expanded: false }))
      );
    } else {
      console.warn("获取投诉历史失败，响应:", res);
    }
  } catch (error) {
    console.error("获取历史投诉失败:", error);
  }
};

// 获取服务人员列表函数
const fetchServicePersonnel = async () => {
  try {
    // 调用 store 中的方法获取服务人员数据
    const allPersonnelData = await usepersonStore.getserverperson();

    // 检查返回的数据是否有效且为数组
    if (Array.isArray(allPersonnelData)) {
      // 使用 map 提取 id 和 name
      servicePersonnel.value = allPersonnelData.map((person) => ({
        id: person.id,
        name: person.name,
      }));
    } else {
      console.warn("getserverperson 未返回有效的数组数据:", allPersonnelData);
      servicePersonnel.value = []; // 或者设置一个默认的空数组
    }
  } catch (error) {
    console.error("获取服务人员列表失败:", error);
    servicePersonnel.value = []; // 发生错误时也设置为空数组
    throw error;
  }
};

onMounted(async () => {
  await Promise.all([fetchComplaintHistory(), fetchServicePersonnel()]);
});

//根据 servicePersonId 从 servicePersonnel 数组获取服务人员姓名
const getServicePersonName = (servicePersonId) => {
  if (servicePersonId === null || servicePersonId === undefined) {
    return "待分配";
  }
  const person = servicePersonnel.value.find((p) => p.id === servicePersonId);
  return person ? person.name : `未知人员 (ID: ${servicePersonId})`;
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return "";
  try {
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const hours = String(date.getHours()).padStart(2, "0");
    const minutes = String(date.getMinutes()).padStart(2, "0");
    return `${year}-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")} ${hours}:${minutes}`;
  } catch (error) {
    console.error("Error formatting date:", dateString, error);
    return dateString;
  }
};
</script>

<style lang="scss" scoped></style>
